package com.iye.puretennis.activity;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.SlideCutListView;
import com.iye.puretennis.domain.CacheType;
import com.iye.puretennis.domain.User;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.DBManager;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.utils.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/12.
 */
public class MyGroupsActivity extends Activity {
    private SlideCutListView listView;
    private List<Group> groups = new ArrayList<Group>();
    DBManager dbManager;
    private MyGroupsAdapter groupsAdapter;
    private String result;
    private ProgressBar mProgress;
    private int mProgressStatus = 0;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mygroups);
        dbManager = new DBManager(this);
        listView = (SlideCutListView) findViewById(R.id.mygroups_list);
        mProgress = (ProgressBar) findViewById(R.id.progress_bar);

        final String cachedMyGroups = dbManager.retrieveMyCachedData(CacheType.MY_GROUPS.name());
        //use cached data to render the view first
        renderMyGroups(cachedMyGroups);


        //an new thread to do ui update in background
        new Thread(new Runnable() {
            @Override
            public void run() {
                    UserToken userToken = dbManager.retrieveCurrentUser();
                    result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.MYGROUPS, userToken.getToken());

                    if (!StringUtils.hasText(cachedMyGroups)) {//没有cache数据，进行cache
                        dbManager.cacheMyData(result, CacheType.MY_GROUPS.name());
                        runOnUiThread(uiUpdateRunnable);
                    } else if (!cachedMyGroups.equals(result)) {//更新cache
                        dbManager.updateMyCachedData(CacheType.MY_GROUPS.name(), result);
                        runOnUiThread(uiUpdateRunnable);
                    }
            }
        }).start();
    }
    //update ui background
    private Runnable uiUpdateRunnable = new Runnable() {
        @Override
        public void run() {

            if(!Constant.RESPONSE_BADLY.equals(result)){
                Toast.makeText(MyGroupsActivity.this,"Data updated!!!!",Toast.LENGTH_SHORT).show();
                renderMyGroups(result);
            }
            mProgress.setVisibility(View.GONE);
        }
    };

    private void renderMyGroups(String jsonStr) {
        if(StringUtils.hasText(jsonStr)){
            try {
                JSONObject groupsJson = new JSONObject(jsonStr);
                JSONArray groupsArrays = groupsJson.getJSONArray("groups");
                for(int i = 0;i<groupsArrays.length();i++){
                    JSONObject groupJson = groupsArrays.getJSONObject(i);
                    String groupGuid = groupJson.getString("groupGuid");
                    String groupName = groupJson.getString("groupName");
                    groups.add(new Group(groupGuid,groupName));
                }
                groupsAdapter = new MyGroupsAdapter(this, R.layout.mygroup_item);
                listView.setAdapter(groupsAdapter);
                listView.setLongClickable(true);
                listView.setOnItemLongClickListener(new GroupItemLongClickListener());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    class MyGroupsAdapter extends BaseAdapter{
        private int resource;//数据绑定在哪个资源界面上
        private LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象
        private ViewCache viewCache;

        MyGroupsAdapter(Context context,int resource) {
            this.resource = resource;
            this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }


        @Override
        public int getCount() {
            return groups.size();
        }

        @Override
        public Object getItem(int position) {
            return groups.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void removeItem(int position){
            groups.remove(position);
            this.notifyDataSetChanged();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView nameView = null;
            TextView amountView = null;
            ImageButton detailBtn = null;

            if(convertView == null){//为第一页显示,创建view对象
                convertView = inflater.inflate(resource, null);//null没有根元素
                nameView = (TextView) convertView.findViewById(R.id.group_name);
                amountView = (TextView) convertView.findViewById(R.id.group_p_amount);
                detailBtn = (ImageButton) convertView.findViewById(R.id.action_mygroup_details);
                viewCache = new ViewCache(nameView,amountView,detailBtn);
                convertView.setTag(viewCache);
            }else{
                viewCache = (ViewCache) convertView.getTag();
                nameView = viewCache.nameView;
                amountView = viewCache.participantsAmountView;
                detailBtn = viewCache.detailBtn;
            }

//            convertView.setOnTouchListener(new GroupItemOnTouchListener(viewCache,detailBtn));
            Group group = groups.get(position);
            nameView.setText(group.name);
            //TODO-- the participants amount of the group
            amountView.setText("0 "+getResources().getString(R.string.ren));
            detailBtn.setOnClickListener(new ButtonListener(position));
            return convertView;
        }
        //group item on touch listener
        class GroupItemOnTouchListener implements View.OnTouchListener{
            private ViewCache holder;
            private float x,ux;
            private ImageButton detailButton;

            GroupItemOnTouchListener(ViewCache holder,ImageButton detailButton) {
                this.holder = holder;
                this.detailButton = detailButton;
            }

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //当按下时处理
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //设置背景为选中状态
                    v.setBackgroundColor(Color.CYAN);
                    //获取按下时的x轴坐标
                    x = event.getX();
                    //判断之前是否出现了删除按钮如果存在就隐藏
                    if (detailButton != null) {
                        detailButton.setVisibility(View.GONE);
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {// 松开处理
                    //设置背景为未选中正常状态
                    v.setBackgroundColor(Color.WHITE);
                    //获取松开时的x坐标
                    ux = event.getX();
                    //判断当前项中按钮控件不为空时
                    if (holder.detailBtn != null) {
                        //按下和松开绝对值差当大于20时显示删除按钮，否则不显示
                        if (Math.abs(x - ux) > 20) {
                            holder.detailBtn.setVisibility(View.VISIBLE);
                        }
                    }
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {//当滑动时背景为选中状态
                    v.setBackgroundColor(Color.CYAN);
                } else {//其他模式
                    //设置背景为未选中正常状态
                    v.setBackgroundColor(Color.WHITE);
                }
                return true;
            }
      }

        //button click listener
        class ButtonListener implements View.OnClickListener{
            private int position;
            private ButtonListener(int position) {
                this.position = position;
            }

            @Override
            public void onClick(View view) {
                int id = view.getId();
                Group group = groups.get(position);
                if(id == viewCache.detailBtn.getId()){
                    TabsActivity parent = (TabsActivity) getParent();
                    FrameLayout tabContentView = parent.tabs.getTabContentView();
                    //删除当前的view
                    tabContentView.removeAllViews();
                    //加载新的view
                    View groupDetailsView = parent.getLayoutInflater().inflate(R.layout.group_details, tabContentView, true);
                    TextView nameTextView = (TextView) groupDetailsView.findViewById(R.id.group_detail_name);
                    nameTextView.setText(group.name);
                }
            }
        }
    }

    class MyGroupActionModeCallback implements ActionMode.Callback{
        int itemPosition;

        MyGroupActionModeCallback(int itemPosition) {
            this.itemPosition = itemPosition;
        }

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
            mode = null;
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.setTitle("Options");
            mode.getMenuInflater().inflate(R.menu.group_item_menu, menu);
            return true;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            int id = item.getItemId();
            switch (id) {
                case R.id.delete:
                    groupsAdapter.removeItem(itemPosition);
                    mode.finish();
                    break;
                case R.id.edit:
                    System.out.println(" edit ");
                    break;
                default:
                    return false;
            }
            return true;
        }
    }

    class GroupItemLongClickListener implements AdapterView.OnItemLongClickListener{

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            startActionMode(new MyGroupActionModeCallback(position));
            view.setSelected(true);
            return false;
        }
    }

    private class Group{
        private String guid;
        private String name;

        public Group(String guid, String name) {
            this.guid = guid;
            this.name = name;
        }
    }

    /**
     * 该类用于缓存View对象,第一页的时候进行创建,第二页数据的时候使用缓存
     * 这种写法的另一个优点是代码数量少占用内存小,另一种是set/get方法
     */
    private final class ViewCache{
        public TextView nameView;
        public TextView participantsAmountView;
        public ImageButton detailBtn;

        public ViewCache(TextView nameView, TextView amountView, ImageButton detailBtn) {
            this.nameView = nameView;
            this.participantsAmountView = amountView;
            this.detailBtn = detailBtn;
        }
    }
}